package screen;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import weibo.http.AccessToken;
import weibo.model.Status;
import weibo.model.User;
import code.Config;
import code.Function;
import ctrl.MyActiveRichTextField;
import ctrl.MyBitmapField;
import ctrl.MyConnectionFactory;
import ctrl.StatusesListStyleButtonField;

public class ShowStatusScreen extends MainScreen
{
    private static final int HPADDING = Display.getWidth() <= 320 ? 4 : 6;
    private static final int VPADDING = 4;

	AccessToken _accessToken;
	Status _status;
	Status _retweet_status;
	User _user;
	String[] _images_status;
	String[] _images_retweet;
	String[] _images_status_middle;
	String[] _images_retweet_middle;
	
	BitmapField _avatar;
	MyBitmapField[] _image_Status;
	MyBitmapField[] _image_Retweet;
	
	VerticalFieldManager _foreground=new VerticalFieldManager(USE_ALL_HEIGHT | VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
	//ListStyleButtonSet _buttonSet=new ListStyleButtonSet();
	StatusesListStyleButtonField _link;
	byte[] avatarData=null;

    DownloadImageThread _connectionThread = new DownloadImageThread();
    
	public ShowStatusScreen(AccessToken accessToken, Status status)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT);
		
        _connectionThread.start();
        
		_accessToken=accessToken;
		_status=status;
		_images_status=_status.getThumbnailImages();
		_images_status_middle=_status.getPicUrls().getMiddlePics();
		_user=_status.getUser();
		_retweet_status=_status.getRetweetedStatus();
		
		HorizontalFieldManager hfm=new HorizontalFieldManager();
		VerticalFieldManager vfm=new VerticalFieldManager();
		
		_avatar=new BitmapField(Bitmap.getBitmapResource("avatar.png"));
		_avatar.setPadding(VPADDING, 0, 0, HPADDING);
		hfm.add(_avatar);
		
		LabelField screenName=new LabelField(_user.getScreenName()) {
			protected void paint(Graphics g)
			{
				g.setColor(Color.WHITE);
				super.paint(g);
			};
		};
		screenName.setFont(Config.FONT_SCREENNAME);
		screenName.setPadding(VPADDING, 0, 0, HPADDING);
		vfm.add(screenName);
		
		MyActiveRichTextField statusField=new MyActiveRichTextField(_status.getText(), Color.WHITE);
		statusField.setPadding(VPADDING, 0, 0, HPADDING*2);
		vfm.add(statusField);
		
		if(_images_status!=null)
		{
			_image_Status=new MyBitmapField[_images_status.length];
			for(int i=0; i<_images_status.length; i++)
			{
				_image_Status[i]=new MyBitmapField(Bitmap.getBitmapResource("status_image.png"), FOCUSABLE);
				_image_Status[i].setMargin(VPADDING, 0, 0, HPADDING*2);
				final String url=_images_status_middle[i];
				_image_Status[i].setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if(context==FieldChangeListener.PROGRAMMATIC) {return;}
						UiApplication.getUiApplication().pushScreen(new ShowStatusImageScreen(url));
					}
				});
				vfm.add(_image_Status[i]);
			}
		}
		
		MyActiveRichTextField retweetField;
		if(_retweet_status!=null)
		{	
			retweetField=new MyActiveRichTextField("@" + _retweet_status.getUser().getScreenName() + " :" + _retweet_status.getText(), Color.ORANGE);
			retweetField.setPadding(VPADDING*2, 0, 0, HPADDING*2);
			vfm.add(retweetField);
			
			_images_retweet=_retweet_status.getThumbnailImages();
			_images_retweet_middle=_retweet_status.getPicUrls().getMiddlePics();
			if(_images_retweet!=null)
			{
				_image_Retweet=new MyBitmapField[_images_retweet.length];
				for(int i=0; i<_images_retweet.length; i++)
				{
					_image_Retweet[i]=new MyBitmapField(Bitmap.getBitmapResource("status_image.png"), FOCUSABLE);
					_image_Retweet[i].setMargin(VPADDING*2, 0, 0, HPADDING*2);
					final String url=_images_retweet_middle[i];
					_image_Retweet[i].setChangeListener(new FieldChangeListener()
					{
						public void fieldChanged(Field field, int context) 
						{
							if(context==FieldChangeListener.PROGRAMMATIC) {return;}
							UiApplication.getUiApplication().pushScreen(new ShowStatusImageScreen(url));
						}
					});
					vfm.add(_image_Retweet[i]);
				}
			}
		}

		_foreground.setBackground(Config.bgColor_Gradient);
		hfm.add(vfm);
		_foreground.add(hfm);
		add(_foreground);
		
		_connectionThread.fetch();
	}
	
	public boolean onClose()
	{
		_connectionThread.stop();
		
		return super.onClose();
	}
	
	class DownloadImageThread extends Thread
    {
        private static final int TIMEOUT = 500;
        private byte[] data;
        
        private MyConnectionFactory factory=null;
        private ConnectionDescriptor descriptor=null;
        private HttpConnection httpConnection=null;
        private InputStream inputStream=null;

        private volatile boolean _fetchStarted = false;
        private volatile boolean _stop = false;

        private void fetch() {_fetchStarted=true;}
        private void stop() {_stop = true;}
        
        private void download(int index, String url, int image_type)
        {
        	descriptor=factory.getConnection(url);
        	
            if(descriptor==null)
            {
            	_fetchStarted=false;
            	stop();
            	return;
            }
            
            httpConnection=(HttpConnection) descriptor.getConnection();
			
            try
            {
				inputStream=httpConnection.openInputStream();
				
				if(inputStream.available()>0)
				{
					data=IOUtilities.streamToBytes(inputStream);

					if(data.length==httpConnection.getLength())
					{
						synchronized(Application.getEventLock())
						{
							try {
								switch (image_type)
				                {
									case Config.IMAGE_TYPE_AVATAR: _avatar.setBitmap(Bitmap.createBitmapFromBytes(data, 0, -1, 1)); break;
									case Config.IMAGE_TYPE_STATUS:
										_image_Status[index].setBitmap(Bitmap.createBitmapFromBytes(data, 0, -1, 1));
										break;
									case Config.IMAGE_TYPE_RETWEET:
										_image_Retweet[index].setBitmap(Bitmap.createBitmapFromBytes(data, 0, -1, 1));	
										break;
								}
							} catch (Exception e) {}
						}
					}
				}
            } catch (IOException e) {}
        }

        public void run()
        {
            for(;;)
            {
                while(!_fetchStarted && !_stop)  
                {
                    try {sleep(TIMEOUT);} catch (InterruptedException e) {Function.errorDialog(StatusesListStyleButtonField.class.getName() + "\n\n" + "Thread#sleep threw " + e.toString());}
                }
                
                if(_stop) {return;}

                if(_status!=null)
                {
                	if(_stop) {return;}
                	
                	String avatar=_status.getUser().getProfileImageUrl();
                	String[] image_status=_status.getThumbnailImages();
                	String[] image_retweet = null;
                	Status retweet=_status.getRetweetedStatus();
                	if(retweet!=null)
                	{
                		if(!retweet.isDeleted()) {image_retweet=retweet.getThumbnailImages();}
                	}
                	
                    factory=new MyConnectionFactory();
                    
                    download(0, avatar, Config.IMAGE_TYPE_AVATAR);
                    if(image_status!=null)
                    {
                    	for(int i=0; i<_images_status.length; i++)
                    	{
                    		download(i, image_status[i], Config.IMAGE_TYPE_STATUS);	
                    	}
                    }
                    
                    if(image_retweet!=null)
                    {
                    	for(int i=0; i<_images_retweet.length; i++)
                    	{
                    		download(i, image_retweet[i], Config.IMAGE_TYPE_RETWEET);	
                    	}
                    }
                }

                if(inputStream!=null) {try {inputStream.close();} catch (Exception e2) {}}
                if(httpConnection!=null) {try {httpConnection.close();} catch (Exception e2) {}}
                
                _fetchStarted = false;           
                stop();
            }
        }
    }
}